

#include "c-utils/utils.h"
#include "c-utils/utils_log.h"

const int pkg_len = 20 * 1000;

int check_value(char *p, int len, char v)
{
    if (*p != v || *(p + len - 1) != v)
    {
        printf("not equal: v: %c, len: %d, p: %p, *p: %c, *(p+len): %c\n", v, len, p, *p, *(p + len - 1));
        return -1;
    }
    return 0;
}

int test_calc(size_t cap, size_t loop)
{

    int ret = -1;
    ringbuf_t *hdl = utils_ringbuf_init(cap, false);
    if (hdl == NULL)
        goto ERROR;
    int i;
    for (i = 0; i < loop; i++)
    {
        void *p1 = utils_ringbuf_malloc(hdl, pkg_len);
        if (p1 == NULL)
        {
            printf("p is null\n");
            goto ERROR;
        }
        void *p2 = utils_ringbuf_malloc(hdl, pkg_len);
        if (p2 == NULL)
        {
            printf("p is null\n");
            goto ERROR;
        }
        void *p3 = utils_ringbuf_malloc(hdl, pkg_len);
        if (p3 == NULL)
        {
            printf("p is null\n");
            goto ERROR;
        }
        memset(p1, 'a', pkg_len);

        memset(p2, 'b', pkg_len);
        memset(p3, 'c', pkg_len);
        if (check_value(p1, pkg_len, 'a') || check_value(p2, pkg_len, 'b') || check_value(p3, pkg_len, 'c'))
        {
            printf("failed\n");
            goto ERROR;
        }
        utils_ringbuf_free(hdl, p1);
        utils_ringbuf_free(hdl, p2);
        utils_ringbuf_free(hdl, p3);
        printf("loop: %d\n", i);
    }
    ret = 0;

ERROR:
    if (hdl)
        utils_ringbuf_destroy(hdl);
    return ret;
}

int test_override(size_t cap, size_t loop)
{
    int ret = -1;
    ringbuf_t *hdl = utils_ringbuf_init(cap, true);
    if (hdl == NULL)
        goto ERROR;
    int i;
    for (i = 0; i < loop; i++)
    {
        void *p = utils_ringbuf_malloc(hdl, pkg_len);
        if (p == NULL)
        {
            printf("p is null\n");
            goto ERROR;
        }
        memset(p, 'a', pkg_len);
        utils_ringbuf_free(hdl, p);
        printf("loop: %d\n", i);
    }
    ret = 0;
ERROR:
    if (hdl)
        utils_ringbuf_destroy(hdl);
    return ret;
}
int test_ringbuf(int argc, char *argv[])
{

    size_t cap = 128 * 1000; // 128KB
    size_t loop = 1000;
    printf("test calc: cap: %ld, loop: %ld.\n", cap, loop);
    if (test_calc(cap, loop))
        return -1;
    printf("test override: cap: %ld, loop: %ld.\n", cap, loop);
    if (test_override(cap, loop))
        return -1;
    printf("done\n");
    return 0;
}